package myJs.user.mission.plot

import myJs.Implicits._
import myJs.Utils._
import myJs.components._
import myJs.myPkg.LayerOptions
import myJs.myPkg.jquery._
import myJs.tool.Pojo._
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.user.FeatureSelectionTool
import myJs.user.workflowMission.featureSelectionResult.FeatureSelectionResult
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, document}
import scalatags.Text.all._
import shared.Pojo.AllPlotData

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.Date
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 2019/4/25
 */
object RocCvTab {

  val curRPlot = RocCv
  val tabId = curRPlot.name

  def init(idStr: String = "", prefix: String = "") = {
    Tool.initMiniColors
    refreshImage(idStr, prefix)
    refreshConfig(idStr, prefix)
    registerEvent(prefix)
  }

  def refreshImage(idStr: String = "", prefix: String = "") = {
    val fileName =RocCvEachTab.getFileName(idStr,prefix,"ROC_Curve_CV_Overall.png")
    val url = g.jsRoutes.controllers.MissionToolController.getWorkspaceImage().url.toString
    val finalTabJq =Tool.getTabJqWithPrefix(tabId,prefix)
    finalTabJq.find(s"img").attr("src",
      s"${url}?missionId=${Tool.getMissionId}&fileName=${fileName}&time=${new Date()}")
  }

  def myRun(prefix: String = "") = {
    val finalTabId = Tool.getTabIdWithPrefix(tabId, prefix)
    val idStr = FeatureSelectionResult.getIdStr
    val bv = $(s"#${finalTabId} #form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(Tool.zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.MissionToolController.plot().url.toString
      val formData = $(s"#${finalTabId} #form").serialize()
      Ajax.post(url = s"${url}", data = s"${formData}&kind=${curRPlot.name}&idStr=${idStr}&prefix=${prefix}",
        headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        layer.close(index)
        val valid = rs("valid").toB
        if (valid) {
          refreshImage(idStr = idStr, prefix = prefix)
        } else {
          g.swal("Error", rs.myGet("message"), "error")
        }
      }
    }
  }

  def registerEvent(prefix: String = "") = {
    val finalTabId = Tool.getTabIdWithPrefix(tabId, prefix)
    $(document.body).offThenOn("click", s"#${finalTabId} .myRun", "", (y: Element) => {
      myRun(prefix)
    })
  }

  def getConfigData(idStr: String = "", prefix: String = "") = {
    val fileName =RocCvEachTab.getFileName(idStr,prefix,curRPlot.configJsonFileName)
    val url = g.jsRoutes.controllers.MissionToolController.getConfigJsonData().url.toString
    Ajax.get(url = s"${url.noCache}&missionId=${Tool.getMissionId}&fileName=${fileName}",
      headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      AllPlotDataTool.getData(rs)
    }
  }

  def refreshFontArg(data: AllPlotData, prefix: String = "") = {
    val finalTabId = Tool.getTabIdWithPrefix(tabId, prefix)
    val state = AllPlotDataTool.getState(data).copy(formJq = $(s"#${finalTabId} #form")).copy(
      xFontShow = true, xTitleFontShow = true,
      yTitleFontShow = true, yFontShow = true,
      mainTitleFontShow = true)
    FontArgComponent.component(state)().renderIntoDOM(document.querySelector(s"#${finalTabId} #myFontArg"))
  }

  def refreshConfig(idStr: String = "", prefix: String = "") = {
    val fileName =RocCvEachTab.getFileName(idStr,prefix,curRPlot.configFileName)
    val finalTabJq =Tool.getTabJqWithPrefix(tabId,prefix)
    val url = g.jsRoutes.controllers.MissionToolController.getConfigData().url.toString
    Ajax.get(url = s"${url.noCache}&missionId=${Tool.getMissionId}&fileName=${fileName}",
      headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn.toMyJDS
      Tool.fillByNames(rs, finalTabJq)
      Tool.fillByNameAndTriggers(rs.toJDJAn, parentJq = finalTabJq)
      bootStrapValidator(finalTabJq)
      val c = FontFamilyComponent.Component().renderIntoDOM(finalTabJq.find("#fontFamily")(0))
      c.setState(FontFamilyComponent.State(rs("fontFamily")))
      getConfigData(idStr, prefix).map { data =>
        refreshFontArg(data, prefix)
      }
    }
  }

  def bootStrapValidator(finalTabJq: JQuery) = {
    val maxNumber = Double.MaxValue
    val basicBVMap = (Tool.getPlotBootstrapValidator.toMap)
    val finalFields = (basicBVMap).toJSDictionary
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> finalFields
    )

    finalTabJq.find(s"#form").bootstrapValidator(dict)
  }

}
